package Gr

import (
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
)

func (cs TableInfoMeta) SeqName(s global.TablesMetaInfoInput) (result global.ObjectNameReturnResult, err error) {
	var f1 any
	var event = "[clusterSeqName]"
	result.BaseResult.Sql = fmt.Sprintf("select NAME from mysql.greatdb_sequences where  db ='%v' %v",
		s.TableInfo.Schema, func() string {
			switch {
			case s.TableInfo.Table == "*":
				return ""
			case strings.Contains(s.TableInfo.Table, "%"):
				return fmt.Sprintf(" and NAME like '%%%v%%'", s.TableInfo.Table)
			default:
				return fmt.Sprintf(" and NAME = '%v'", s.TableInfo.Table)
			}
		}())
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.StringGarth,
	}); err != nil || f1 == nil {
		return
	}
	result.Result = f1.([]string)
	return
}

func (cs TableInfoMeta) SeqExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var f1 any
	var event = "[clusterSeqExist]"
	result.BaseResult.Sql = fmt.Sprintf("select count(1) as `sum` from mysql.greatdb_sequences where  db ='%v'  and name = '%v'", s.TableInfo.Schema, s.TableInfo.Table)
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil || f1 == nil {
		return
	}
	if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
		result.Result = true
	}
	return
}

func seqPrintInfo(x global.SeqResultDefinition) string {
	var (
		cache = "NOCACHE"
		order = "NOORDER"
		cycle = "NOCYCLE"
	)
	if x.CacheSize != "0" {
		cache = fmt.Sprintf("CACHE %v", x.CacheSize)
	}
	if x.OrderFlag != "0" {
		order = "ORDER"
	}
	if x.CycleFlag != "0" {
		order = "CYCLE"
	}
	return fmt.Sprintf("CREATE SEQUENCE `%v`.`%v` \n"+
		"\t MINVALUE %v \n"+
		"\t MAXVALUE %v \n"+
		"\t INCREMENT BY %v \n"+
		"\t START WITH %v \n "+
		"\t %v %v %v \n", x.Schema, x.Name, x.MinValue, x.MaxValue, x.IncrementBy, x.StartValue, cache, order, cycle)
}

func (cs SchemaObjectMeta) Seq(s global.SchemaObjectInput) (result global.SchemaObjectReturnResult, err error) {
	var (
		f1    any
		event = "[clusterSeq]"
		x     global.SeqResultDefinition
	)
	result.BaseResult.Sql = fmt.Sprintf("SELECT \n"+
		"\t`db` AS `schema`,\n"+
		"\t`name` AS `name`,\n"+
		"\t`minvalue` AS `minValue`,\n"+
		"\t`maxvalue` AS `maxValue`,\n"+
		"\t`increment` AS `incrementBy`,\n"+
		"\t`cycle_flag` AS `cycleFlag`,\n"+
		"\t`order_flag` AS `orderFlag`,\n"+
		"\t`cache_num` AS `cacheSize`,\n"+
		"\t`start_with` AS `startValue` \n"+
		"\tFROM  \n"+
		"\t `mysql`.`greatdb_sequences` \n"+
		"\t WHERE \n"+
		"\t `db`='%v' and `name`='%v'", s.Schema, s.Table)
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil || f1 == nil {
		return
	}
	if err = global.MapSubToStructSubJsonName(mapNullActive(f1.(map[string]any)), &x); err != nil {
		return
	}
	x.Type = "seq"
	x.PrintInfo = seqPrintInfo(x)
	result.SeqResult.Definition = x
	result.SeqResult.Convert = global.SeqDefinitionConvertS{
		Schema:      x.Schema,
		Name:        x.Name,
		MinValue:    x.MinValue,
		MaxValue:    x.MaxValue,
		IncrementBy: x.IncrementBy,
		CycleFlag:   x.CycleFlag,
		OrderFlag:   x.OrderFlag,
		CacheSize:   x.CacheSize,
		StartValue:  x.StartValue,
		Type:        x.Type,
		PrintInfo:   x.PrintInfo,
	}
	return
}

func createSeq(s global.SchemaObjectInput) (res global.ObjectFixSqlS, err error) {
	var (
		cache = "NOCACHE"
		order = "NOORDER"
		cycle = "NOCYCLE"
	)
	if s.ObjectDefinition.SeqResult.Convert.CacheSize != "0" {
		cache = fmt.Sprintf("CACHE %v", s.ObjectDefinition.SeqResult.Convert.CacheSize)
	}
	if s.ObjectDefinition.SeqResult.Convert.OrderFlag != "N" {
		order = "ORDER"
	}
	if s.ObjectDefinition.SeqResult.Convert.CycleFlag != "N" {
		cycle = "CYCLE"
	}
	res.CreateSql = append(res.CreateSql, fmt.Sprintf("use %v; \n"+
		"CREATE SEQUENCE \"%v\".\"%v\" \n"+
		"\t MINVALUE %v \n"+
		"\t MAXVALUE %v \n"+
		"\t INCREMENT BY %v \n"+
		"\t START WITH %v \n "+
		"\t %v %v %v ; \n",
		s.Schema, s.Schema, s.ObjectDefinition.SeqResult.Convert.Name, s.ObjectDefinition.SeqResult.Convert.MinValue, s.ObjectDefinition.SeqResult.Convert.MaxValue, s.ObjectDefinition.SeqResult.Convert.IncrementBy, s.ObjectDefinition.SeqResult.Convert.StartValue, cache, order, cycle))
	return
}
